package service

import (
	"github.com/go-redis/redis"
	"github.com/jinzhu/gorm"
	"micro-oauth/config"
	"micro-oauth/repo"
	repoCache "micro-oauth/repo/cache"
	"micro-oauth/service/admin"
	"micro-oauth/service/cache"
	"micro-oauth/service/oauth"
	"micro-oauth/service/vendor_account"
	"log"
)

var OauthService oauth.OauthServiceInterface
var VendorService vendor_account.VendorAccountService
var AdminService admin.AdminServiceInterface
var CacheService cache.CacheServiceInterface

func init() {
	pgArgs := config.LoadPGArgs()
	dbConf := config.LoadDatabaseConfig()
	db, err := gorm.Open("postgres", pgArgs)
	if err != nil {
		log.Fatal(err)
	}
	db.DB().SetMaxOpenConns(dbConf.MaxOpenConns)
	db.DB().SetMaxIdleConns(dbConf.MaxIdleConns)
	redisConfig := config.LoadRedisConfig()
	option := &redis.Options{
		Addr: redisConfig.Host + ":" + redisConfig.Port,
		//Password: redisConfig.Pwd,
	}
	redisClient := redis.NewClient(option)
	cacheService := cache.NewCacheService(redisClient)

	repoCacheService := repoCache.NewRedisCacheService(redisClient)
	repoService := repo.NewService(db, repoCacheService)

	OauthService = oauth.NewOauthService(repoService, cacheService, config.JWTSignSecret)
	AdminService = admin.NewAdminService(repoService, cacheService)
	VendorService = vendor_account.NewVendorAccountService(repoService)
	CacheService = cache.NewCacheService(redisClient)
}
